import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { CreateWorkDto } from './dto/create-work.dto';
import { UpdateWorkDto } from './dto/update-work.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Work } from './entities/work.entity';
import { QueryWorkF } from './dto/query-work.dto';

@Injectable()
export class WorksService {
  constructor(
    @InjectRepository(Work)
    private workRepository: Repository<Work>,
  ) {}
  create(createWorkDto: CreateWorkDto) {
    const createWork = this.workRepository.create(createWorkDto);
    return this.workRepository.save(createWork);
  }

  findAll(query: QueryWorkF) {
    const findObj = {};
    Object.keys(query).forEach((key) => {
      if (query[key]) {
        findObj[key] = query[key];
      }
    });
    return this.workRepository.find({ where: findObj });
  }

  findOne(id: string) {
    return this.workRepository.findOne({ where: { id: id } });
  }

  async update(id: string, updateWorkDto: UpdateWorkDto) {
    const existWork = await this.workRepository.findOne({ where: { id: id } });
    if (!existWork) {
      throw new HttpException(`不存在id为${id}的作品`, HttpStatus.BAD_REQUEST);
    }
    const updateWork = this.workRepository.merge(existWork, updateWorkDto);
    return this.workRepository.save(updateWork);
  }

  remove(id: string) {
    return this.workRepository.delete(id);
  }
}
